package com.cqeec.waimaidemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cqeec.waimaidemo.common.R;
import com.cqeec.waimaidemo.dto.SetmealDto;
import com.cqeec.waimaidemo.entity.Category;
import com.cqeec.waimaidemo.entity.Setmeal;
import com.cqeec.waimaidemo.service.CategoryService;
import com.cqeec.waimaidemo.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    SetmealService setmealService;
    @Autowired
    CategoryService categoryService;
//   新增套餐
    @PostMapping
    public R<String> addSetMeal(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithDish(setmealDto);
        return R.success("新增套餐成功");
    }
//套餐模糊分页查询
@GetMapping("/page")
public R<Page> getPage(int page, int pageSize,String name){
    Page<Setmeal> pageInfo=new Page<>(page,pageSize);
    LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
//    根据字段sort升序
    queryWrapper.like(name!=null,Setmeal::getName,name);
    queryWrapper.orderByAsc(Setmeal::getUpdateTime);
    setmealService.page(pageInfo,queryWrapper);
    Page<SetmealDto> dtoPage=new Page<>(page,pageSize);
    BeanUtils.copyProperties(pageInfo,dtoPage);
    List<SetmealDto> list=pageInfo.getRecords().stream().map(item->{
        SetmealDto setmealDto=new SetmealDto();
        BeanUtils.copyProperties(item,setmealDto);
        Category category = categoryService.getById(item.getCategoryId());
        if (category!=null){
            setmealDto.setCategoryName(category.getName());
        }
        return  setmealDto;
    }).collect(Collectors.toList());
    dtoPage.setRecords(list);
    return R.success(dtoPage);
}
@DeleteMapping
    public R<String> deleteSetMeal(@RequestParam List<Long> ids){
        setmealService.removeWithDish(ids);
        return R.success("删除成功");
}
}
